package org.black.phoneUtility.sms.schedule.app.fragment;

import java.util.Calendar;

import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.schedule.database.dataModel.SmsSchedule;
import org.black.phoneUtility.sms.schedule.provider.SmsScheduleContract;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class SmsScheduleRepeatFragment extends Fragment implements
		OnItemSelectedListener, View.OnClickListener,
		CompoundButton.OnCheckedChangeListener {
	public static final String TAG = SmsScheduleRepeatFragment.class.getName();
	private static final String LOG_TAG = SmsScheduleRepeatFragment.class
			.getName();
	public static final String ARGUMENTS_SMS_SCHEDULE = "arguments_sms_schedule";

	private SmsSchedule smsSchedule;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getActivity().onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().setTitle(getString(R.string.sms_schedule_repeat_title));

		getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
		getActivity().getActionBar().setTitle(
				getString(R.string.sms_schedule_repeat_title));
		getActivity().getActionBar().setDisplayOptions(
				ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE
						| ActionBar.DISPLAY_SHOW_HOME);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View result = inflater.inflate(R.layout.sms_schedule_repeat_edit,
				container, false);
		this.smsSchedule = (SmsSchedule) getArguments().getSerializable(
				ARGUMENTS_SMS_SCHEDULE);
		Spinner repeatSpinner = (Spinner) result
				.findViewById(R.id.smsScheduleRepeatSpinner);
		ArrayAdapter<CharSequence> repeatSpinnerAdapter = ArrayAdapter
				.createFromResource(this.getActivity(),
						R.array.sms_schedule_repeat_type_array,
						android.R.layout.simple_spinner_item);
		repeatSpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		repeatSpinner.setAdapter(repeatSpinnerAdapter);
		repeatSpinner.setOnItemSelectedListener(this);
		int repeatPosition = 0;
		switch (this.smsSchedule.getRepeatType()) {
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_NONE:
			repeatPosition = 0;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_EVERY_MINUTE:
			repeatPosition = 1;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_HOURLY:
			repeatPosition = 2;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_DAILY:
			repeatPosition = 3;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_WEEKLY:
			repeatPosition = 4;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_MONTHLY:
			repeatPosition = 5;
			break;
		case SmsScheduleContract.SmsSchedules.REPEAT_TYPE_YEARLY:
			repeatPosition = 6;
			break;
		}
		repeatSpinner.setSelection(repeatPosition);

		Button repeatButton = (Button) result
				.findViewById(R.id.smsScheduleRepeatButton);
		repeatButton.setOnClickListener(this);

		Spinner endSpinner = (Spinner) result
				.findViewById(R.id.smsScheduleRepeatOnEndSpinner);
		ArrayAdapter<CharSequence> endSpinnerAdapter = ArrayAdapter
				.createFromResource(this.getActivity(),
						R.array.sms_schedule_repeat_on_ends_type_array,
						android.R.layout.simple_spinner_item);
		endSpinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		endSpinner.setAdapter(endSpinnerAdapter);
		endSpinner.setOnItemSelectedListener(this);
		int endPosition = 0;
		switch (this.smsSchedule.getEndType()) {
		case SmsScheduleContract.SmsSchedules.END_TYPE_NEVER:
			endPosition = 0;
			break;
		case SmsScheduleContract.SmsSchedules.END_TYPE_AFTER_TIMES:
			endPosition = 1;
			break;
		case SmsScheduleContract.SmsSchedules.END_TYPE_ON_SPECIFIC_DATETIME:
			endPosition = 2;
			break;
		default:
			break;
		}
		endSpinner.setSelection(endPosition);

		Button afterButton = (Button) result
				.findViewById(R.id.smsScheduleRepeatOnEndAfterButton);
		afterButton.setOnClickListener(this);

		Button onButton = (Button) result
				.findViewById(R.id.smsScheduleRepeatOnEndOnButton);
		onButton.setOnClickListener(this);
		ToggleButton sundayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatSundayToggleButton);
		sundayButton.setChecked(this.smsSchedule.isRepeatOnSunday());
		ToggleButton mondayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatMondayToggleButton);
		mondayButton.setChecked(this.smsSchedule.isRepeatOnMonday());
		ToggleButton tuesdayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatTuesdayToggleButton);
		tuesdayButton.setChecked(this.smsSchedule.isRepeatOnTuesday());
		ToggleButton wednesdayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatWednesdayToggleButton);
		wednesdayButton.setChecked(this.smsSchedule.isRepeatOnWednesday());
		ToggleButton thursdayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatThursdayToggleButton);
		thursdayButton.setChecked(this.smsSchedule.isRepeatOnThursday());
		ToggleButton fridayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatFridayToggleButton);
		fridayButton.setChecked(this.smsSchedule.isRepeatOnFriday());
		ToggleButton saturdayButton = (ToggleButton) result
				.findViewById(R.id.smsScheduleRepeatEveryRepeatSaturdayToggleButton);
		saturdayButton.setChecked(this.smsSchedule.isRepeatOnSaturday());

		sundayButton.setOnCheckedChangeListener(this);
		mondayButton.setOnCheckedChangeListener(this);
		tuesdayButton.setOnCheckedChangeListener(this);
		wednesdayButton.setOnCheckedChangeListener(this);
		thursdayButton.setOnCheckedChangeListener(this);
		fridayButton.setOnCheckedChangeListener(this);
		saturdayButton.setOnCheckedChangeListener(this);
		return result;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		int viewId = parent.getId();
		if (viewId == R.id.smsScheduleRepeatSpinner) {
			int repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_NONE;
			if (pos == 0) {
				getView().findViewById(
						R.id.smsScheduleScheduleRepeatSettingRelativeLayout)
						.setVisibility(View.GONE);
				getView().findViewById(
						R.id.smsScheduleScheduleRepeatEndSettingRelativeLayout)
						.setVisibility(View.GONE);
				repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_NONE;
			} else {
				getView().findViewById(
						R.id.smsScheduleScheduleRepeatSettingRelativeLayout)
						.setVisibility(View.VISIBLE);
				getView().findViewById(
						R.id.smsScheduleScheduleRepeatEndSettingRelativeLayout)
						.setVisibility(View.VISIBLE);
				Integer repeatEvery = this.smsSchedule.getRepeatEvery() == null ? 1
						: this.smsSchedule.getRepeatEvery();

				Resources resources = this.getResources();
				int quantityStringId = 0;
				View dayOfWeekLinearLayout = getView().findViewById(
						R.id.smsScheduleRepeatEveryDayOfWeekLinearLayout);
				dayOfWeekLinearLayout.setVisibility(View.GONE);
				if (pos == 0) {
				} else if (pos == 1) {
					quantityStringId = R.plurals.minutes;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_EVERY_MINUTE;
					if (repeatEvery > 60) {
						repeatEvery = 60;
					}
				} else if (pos == 2) {
					quantityStringId = R.plurals.hours;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_HOURLY;
					if (repeatEvery > 24) {
						repeatEvery = 24;
					}
				} else if (pos == 3) {
					quantityStringId = R.plurals.days;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_DAILY;
					if (repeatEvery > 7) {
						repeatEvery = 7;
					}
				} else if (pos == 4) {
					quantityStringId = R.plurals.weeks;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_WEEKLY;
					dayOfWeekLinearLayout.setVisibility(View.VISIBLE);
					if (repeatEvery > 52) {
						repeatEvery = 52;
					}
				} else if (pos == 5) {
					quantityStringId = R.plurals.months;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_MONTHLY;
					if (repeatEvery > 12) {
						repeatEvery = 12;
					}
				} else if (pos == 6) {
					quantityStringId = R.plurals.years;
					repeatType = SmsScheduleContract.SmsSchedules.REPEAT_TYPE_YEARLY;
					if (repeatEvery > 10) {
						repeatEvery = 10;
					}
				}
				if (pos != 0) {
					this.smsSchedule.setRepeatEvery(repeatEvery);
				}

				((Button) getView().findViewById(
						R.id.smsScheduleRepeatOnEndAfterButton))
						.setText(repeatEvery.toString());
				((TextView) getView().findViewById(
						R.id.smsScheduleRepeatTimesTextView)).setText(resources
						.getQuantityString(quantityStringId, repeatEvery,
								repeatEvery));
			}

			this.handleRepeatEvery(repeatType,
					this.smsSchedule.getRepeatEvery());
		} else if (viewId == R.id.smsScheduleRepeatOnEndSpinner) {
			int endType = SmsScheduleContract.SmsSchedules.END_TYPE_NEVER;
			if (pos == 0) {
				getView().findViewById(
						R.id.smsScheduleEndOnEndAfterRelativeLayout)
						.setVisibility(View.GONE);
				getView().findViewById(
						R.id.smsScheduleRepeatOnEndOnRelativeLayout)
						.setVisibility(View.GONE);
				endType = SmsScheduleContract.SmsSchedules.END_TYPE_NEVER;
			} else if (pos == 1) {
				getView().findViewById(
						R.id.smsScheduleEndOnEndAfterRelativeLayout)
						.setVisibility(View.VISIBLE);
				getView().findViewById(
						R.id.smsScheduleRepeatOnEndOnRelativeLayout)
						.setVisibility(View.GONE);
				endType = SmsScheduleContract.SmsSchedules.END_TYPE_AFTER_TIMES;
			} else if (pos == 2) {
				getView().findViewById(
						R.id.smsScheduleEndOnEndAfterRelativeLayout)
						.setVisibility(View.GONE);
				getView().findViewById(
						R.id.smsScheduleRepeatOnEndOnRelativeLayout)
						.setVisibility(View.VISIBLE);
				endType = SmsScheduleContract.SmsSchedules.END_TYPE_ON_SPECIFIC_DATETIME;

			}

			this.handleRepeatEnd(
					endType,
					this.smsSchedule.getEndAfterTimes(),
					this.smsSchedule.getEndOnSpecificDateTime() == null ? null
							: Long.valueOf(this.smsSchedule
									.getEndOnSpecificDateTime().getTime()));
		} else {
			Log.e(LOG_TAG, "viewId: " + viewId + " does not match any layout!");
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	public void handleRepeatEvery(int repeatType, Integer number) {
		this.smsSchedule.setRepeatType(repeatType);
		if (repeatType != SmsScheduleContract.SmsSchedules.REPEAT_TYPE_NONE) {
			this.smsSchedule.setRepeatEvery(number);
			if (number != null) {
				((Button) getView().findViewById(R.id.smsScheduleRepeatButton))
						.setText(String.valueOf(number));
				int quantityStringId = 0;

				if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_EVERY_MINUTE) {
					quantityStringId = R.plurals.minutes;
				} else if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_HOURLY) {
					quantityStringId = R.plurals.hours;
				} else if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_DAILY) {
					quantityStringId = R.plurals.days;
				} else if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_WEEKLY) {
					quantityStringId = R.plurals.weeks;
				} else if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_MONTHLY) {
					quantityStringId = R.plurals.months;
				} else if (repeatType == SmsScheduleContract.SmsSchedules.REPEAT_TYPE_YEARLY) {
					quantityStringId = R.plurals.years;
				}
				((TextView) getView().findViewById(
						R.id.smsScheduleRepeatTimesTextView))
						.setText(getActivity().getResources()
								.getQuantityString(quantityStringId, number,
										number));
			}
		}
	}

	public void handleRepeatEnd(int endType, Integer endTimes, Long endTime) {
		this.smsSchedule.setEndType(endType);
		if (endType == SmsScheduleContract.SmsSchedules.END_TYPE_NEVER) {
		} else if (endType == SmsScheduleContract.SmsSchedules.END_TYPE_AFTER_TIMES) {
			Button smsScheduleRepeatOnEndAfterButton = (Button) getView()
					.findViewById(R.id.smsScheduleRepeatOnEndAfterButton);
			if (endTimes == null) {
				endTimes = 10;
			}
			this.smsSchedule.setEndAfterTimes(endTimes);
			smsScheduleRepeatOnEndAfterButton.setText(endTimes.toString());
			((TextView) getView().findViewById(
					R.id.smsScheduleRepeatOnEndAfterTimesTextView))
					.setText(getActivity().getResources().getQuantityString(
							R.plurals.times,
							this.smsSchedule.getEndAfterTimes(),
							this.smsSchedule.getEndAfterTimes()));
		} else if (endType == SmsScheduleContract.SmsSchedules.END_TYPE_ON_SPECIFIC_DATETIME) {
			Button smsScheduleRepeatOnEndOnButton = (Button) getView()
					.findViewById(R.id.smsScheduleRepeatOnEndOnButton);
			Calendar calendar = Calendar.getInstance();
			if (endTime != null) {
				calendar.setTimeInMillis(endTime);
			} else {
				calendar.add(Calendar.DAY_OF_YEAR, 7);
			}
			calendar.set(Calendar.MILLISECOND, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.HOUR_OF_DAY, 0);
			smsScheduleRepeatOnEndOnButton.setText(DateFormat.getDateFormat(
					getActivity()).format(calendar.getTimeInMillis()));
			this.smsSchedule.setEndOnSpecificDateTime(calendar.getTime());
		} else {
			throw new UnsupportedOperationException(
					"endType not support! endType: " + endType);
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.smsScheduleRepeatButton) {
			SmsScheduleRepeatEveryDialogFragment smsScheduleRepeatEveryDialogFragment = new SmsScheduleRepeatEveryDialogFragment();
			Bundle bundle = new Bundle();
			bundle.putInt(
					SmsScheduleRepeatEveryDialogFragment.ARGUMENTS_REPEAT_TYPE,
					this.smsSchedule.getRepeatType());
			bundle.putInt(
					SmsScheduleRepeatEveryDialogFragment.ARGUMENTS_REPEAT_EVERY_VALUE,
					this.smsSchedule.getRepeatEvery() == null ? 1
							: this.smsSchedule.getRepeatEvery());
			smsScheduleRepeatEveryDialogFragment.setArguments(bundle);
			smsScheduleRepeatEveryDialogFragment.show(getFragmentManager(),
					SmsScheduleRepeatEveryDialogFragment.TAG);
		} else if (v.getId() == R.id.smsScheduleRepeatOnEndAfterButton) {
			SmsScheduleRepeatEndAfterDialogFragment smsScheduleRepeatEndAfterDialogFragment = new SmsScheduleRepeatEndAfterDialogFragment();
			Bundle bundle = new Bundle();
			bundle.putInt(
					SmsScheduleRepeatEndAfterDialogFragment.ARGUMENTS_REPEAT_END_AFTER_TIMES,
					this.smsSchedule.getEndAfterTimes() == null ? 10
							: this.smsSchedule.getEndAfterTimes());
			smsScheduleRepeatEndAfterDialogFragment.setArguments(bundle);
			smsScheduleRepeatEndAfterDialogFragment.show(getFragmentManager(),
					SmsScheduleRepeatEndAfterDialogFragment.TAG);

		} else if (v.getId() == R.id.smsScheduleRepeatOnEndOnButton) {
			SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment smsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment = new SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment();
			Calendar calendar = Calendar.getInstance();
			if (this.smsSchedule.getEndOnSpecificDateTime() != null) {
				calendar.setTimeInMillis(this.smsSchedule
						.getEndOnSpecificDateTime().getTime());
			} else {
				calendar.add(Calendar.DAY_OF_YEAR, 7);
			}
			Bundle bundle = new Bundle();
			bundle.putInt(
					SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment.ARGUMENTS_YEAR,
					calendar.get(Calendar.YEAR));
			bundle.putInt(
					SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment.ARGUMENTS_MONTH,
					calendar.get(Calendar.MONTH));
			bundle.putInt(
					SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment.ARGUMENTS_DATE,
					calendar.get(Calendar.DAY_OF_MONTH));
			smsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment
					.setArguments(bundle);
			smsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment
					.show(getFragmentManager(),
							SmsScheduleRepeatEndOnSpecificDateDatePickerDialogFragment.TAG);
			this.smsSchedule.setEndOnSpecificDateTime(calendar.getTime());

		}

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatSundayToggleButton) {
			this.smsSchedule.setRepeatOnSunday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatMondayToggleButton) {
			this.smsSchedule.setRepeatOnMonday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatTuesdayToggleButton) {
			this.smsSchedule.setRepeatOnTuesday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatWednesdayToggleButton) {
			this.smsSchedule.setRepeatOnWednesday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatThursdayToggleButton) {
			this.smsSchedule.setRepeatOnThursday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatFridayToggleButton) {
			this.smsSchedule.setRepeatOnFriday(isChecked);
		} else if (buttonView.getId() == R.id.smsScheduleRepeatEveryRepeatSaturdayToggleButton) {
			this.smsSchedule.setRepeatOnSaturday(isChecked);
		}

	}
}
